import Vue from 'vue'
import Router from 'vue-router'
import Axios from "axios";
if (localStorage.getItem("token") != null) {
  Axios.defaults.headers.common["token"] = localStorage.getItem("token");
}
Vue.use(Router)

const WelcomeComp = {
  path: '/',
  name: 'Welcome',
  component: () => import("@/components/WelcomeComp")
}
const NoPerm = {
  path: '/403',
  name: 'NoPerm',
  component: () => import("@/components/NoPerm")
}
const UserComp = {
  path: '/user',
  name: 'User',
  component: () => import("@/components/manage/UserComp")
}
const OrderComp = {
  path: '/order',
  name: 'Order',
  component: () => import("@/components/manage/OrderComp")
}
const RiderComp = {
  path: '/rider',
  name: 'Rider',
  component: () => import("@/components/manage/RiderComp")
}
const AdminComp = {
  path: '/admin',
  name: 'Admin',
  component: () => import("@/components/manage/AdminComp")
}
const RoleComp = {
  path: '/role',
  name: 'Role',
  component: () => import("@/components/manage/RoleComp")
}
const DiscountComp = {
  path: '/discount',
  name: 'Discount',
  component: () => import("@/components/manage/DiscountComp")
}
const ChangePwdComp = {
  path: '/changepwd',
  name: 'ChangePwd',
  component: () => import("@/components/ChangePwdComp")
}
const NotFound = {
  path: '/*',
  name: 'NotFound',
  component: () => import("@/components/NotFound")
}

const router = new Router({

})

const AllRouters = [
  UserComp, OrderComp,RiderComp,AdminComp,RoleComp,DiscountComp
]

const MyRouters = [
  WelcomeComp, NoPerm,ChangePwdComp
]

Axios.get("/tfss/admin/getMenuById").then((r) => {
  if (r.data.code == 200) {
    for (const router of AllRouters) {
      for (const menu of r.data.data) {
        if (menu.link == router.path) {
          MyRouters.push(router)
        }
      }
    };
    MyRouters.push(NotFound)
    router.addRoutes(MyRouters)
  }
});


router.beforeEach((to, from, next) => {
  if (to.path == "/logout") {
    localStorage.removeItem("token")
    localStorage.removeItem("account")
    location.href = "/login.html"
    return
  }
  if (to.path == "/403") {
    next()
    return
  }
  if (!localStorage.getItem("token")) {
    location.href = "/login.html"
    return
  }
  next()
})

export default router;
